//
//  BaseNode+Extension.swift
//  MarkdownUIKit
//
//  Created by nowcoder on 2025/1/8.
//

import Foundation
import Down

extension BaseNode {
    
    private struct AssociationKey {
        static var isSkipProcessingKey = "isSkipProcessingKey"
    }
    
    var parent: Node? {
        cmarkNode.parent?.wrap()
    }
    
    var nextNode: Node? {
        guard let parent else { return nil }
        if let nextIndex = parent.children.firstIndex(where: { $0.cmarkNode.literal == cmarkNode.literal }),
           parent.children.count > (nextIndex + 1) {
            return parent.children[(nextIndex + 1)]
        }
        return nil
    }
    
    var isSkipProcessing: Bool {
        get {
            guard parent != nil else { return false }
            // 打印当前节点的指针
            print("isSkipProcessing get current node(\(cmarkNode.literal ?? "--") pointer: \(Unmanaged.passUnretained(self).toOpaque())")
            return objc_getAssociatedObject(self, &AssociationKey.isSkipProcessingKey) as? Bool ?? false
        }
        
        set {
            guard parent != nil else { return }
            // 打印当前节点的指针
            print("isSkipProcessing set current node(\(cmarkNode.literal ?? "--") pointer: \(Unmanaged.passUnretained(self).toOpaque())")
            objc_setAssociatedObject(
                self,
                &AssociationKey.isSkipProcessingKey,
                newValue,
                .OBJC_ASSOCIATION_RETAIN
            )
        }
    }
}
